package com.miracle.auth;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miracle.entity.User;
import com.miracle.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author jie.xi
 * @date 2022年05月18日 13:13
 */

@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        //查找到对应用户的数据
        User user = userService.getOne(wrapper);
        if (user == null){
            throw new UsernameNotFoundException("未查找到该用户");
        }
        MyUserDetail myUserDetail = new MyUserDetail();
        myUserDetail.setUser(user);
        myUserDetail.setUsername(user.getUsername());
        myUserDetail.setPassword("{noop}"+user.getPassword());
        //查找该用户的权限
        List<String> userRolesById = userService.getUserRolesById(user.getId());
        if(userRolesById.size()>0){
            Set<GrantedAuthority> authoritySet = new HashSet<>();
            for(String role :  userRolesById){
                authoritySet.add(new SimpleGrantedAuthority(role));
            }
            myUserDetail.setAuthorities(authoritySet);
        }
        System.out.println(myUserDetail);
        return myUserDetail;
    }
}
